package com.gusha.app;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.gusha.config.SysOperateLog;
import com.gusha.dao.InfoContentDao;
import com.gusha.dao.ReplyCommDao;
import com.gusha.dao.SysCommentDao;
import com.gusha.dao.SysProductsDao;
import com.gusha.dao.SysScenicDao;
import com.gusha.dao.SysTicketDao;
import com.gusha.dao.SysTicketTypeDao;
import com.gusha.dao.SysTrainingDao;
import com.gusha.dao.TrainCommDao;
import com.gusha.dao.UserDao;
import com.gusha.model.InfoContent;
import com.gusha.model.ReplyComm;
import com.gusha.model.SysAdmin;
import com.gusha.model.SysClassify;
import com.gusha.model.SysComment;
import com.gusha.model.SysProducts;
import com.gusha.model.SysScenic;
import com.gusha.model.SysTicket;
import com.gusha.model.SysTicketType;
import com.gusha.model.SysTraining;
import com.gusha.model.TrainComm;
import com.gusha.model.User;
import com.gusha.service.InfoContentService;
import com.gusha.service.ReplyCommService;
import com.gusha.service.SysCommentService;
import com.gusha.service.SysProductsService;
import com.gusha.service.SysTrainingService;
import com.gusha.utils.BarcodeUtil;
import com.gusha.utils.Constants;
import com.gusha.utils.FileUtils;
import com.gusha.utils.JsonResult;
import com.gusha.utils.RandomUtil;
import com.gusha.utils.UpdateUtil;
import com.gusha.utils.WebValueUtil;

import sun.misc.BASE64Decoder;

@CrossOrigin(origins="*",maxAge=3600)
@Controller
@RequestMapping("/app")
public class AppHomeController {

	@Autowired
	private InfoContentDao infoContentDao;
	@Autowired
	private SysProductsDao sysProductsDao;
	@Autowired
	private SysProductsService sysProductsService;
	@Autowired
	private InfoContentService infoContentService;
	@Autowired
	private SysCommentService sysCommentService;
	@Autowired
	private SysCommentDao sysCommentDao;
	@Autowired
	private SysScenicDao sysScenicDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private SysTrainingDao sysTrainingDao;
	@Autowired
	private SysTrainingService sysTrainingService;
	@Autowired
	private TrainCommDao trainCommDao;
	
	@Autowired
	private SysTicketTypeDao sysTicketTypeDao;
	
	@Autowired
	private SysTicketDao sysTicketDao;
	@Autowired
	private ReplyCommDao replyCommDao;
	
	@Autowired
	private ReplyCommService replyCommService;
	
	//首页
	@CrossOrigin(origins="*",maxAge=3600)
	@PostMapping("/toHome")
	@ResponseBody
	public JsonResult toHome() {
		JsonResult result=new JsonResult(false);
		
		//List<SysProducts> listSysProducts= sysProductsDao.findAll();
	
		//List<InfoContent> listInfoContent= infoContentDao.findAll();
	 
		//List<InfoContent> list=infoContentDao.fingAllByClickNum("clickNum");
		//查询点击量top4
		InfoContent infoContent=new InfoContent();
		 Sort sort = new Sort(Sort.Direction.DESC, "clickNum");
	        Pageable pageable = PageRequest.of(0, 4, sort);
	        Page<InfoContent> page = infoContentService.findAll(pageable, infoContent);
	        
	        SysProducts sysProducts=new SysProducts();  
	        Sort sort1 = new Sort(Sort.Direction.DESC, "clickMun");
	        Pageable pageable1 = PageRequest.of(0, 4, sort1);
	        Page<SysProducts> page1 = sysProductsService.findAll(pageable1, sysProducts);
	        
	        
	        SysTraining sysTraining=new SysTraining();
	        Sort sort2=new Sort(Sort.Direction.DESC, "addTime");
	        Pageable pageable2 = PageRequest.of(0, 4, sort2);
	        Page<SysTraining> page2=sysTrainingService.findAll(pageable2, sysTraining);
	        
		//List<SysProducts> listp=sysProductsDao.fingAllByClickNum("clickNum");
		Map<String,Object> objMap= new HashMap<String,Object>();
		objMap.put("toplist",page);//资讯推荐 
		objMap.put("toplistPro",page1);//产品推荐
		objMap.put("trainTop", page2);//新鲜培训推荐

		//objMap.put("listSysProducts", listSysProducts);//产品全部
		//objMap.put("listInfoContent", listInfoContent);//资讯全部
		result.setObj(objMap);
		result.setMsg("操作成功");
		result.setFlag(true);
		return result;
		
	}
	//资讯列表
	@CrossOrigin(origins="*",maxAge=3600)
	@PostMapping("/contentList")
	@ResponseBody
	public JsonResult contentList(Model model, HttpServletRequest request) {
		JsonResult result=new JsonResult(false);
		 String pageIndex = WebValueUtil.getWebValue(request, "pageIndex");
		 int pageNo = 0;
	        if (StringUtils.isNotBlank(pageIndex)) {
	            pageNo = Integer.parseInt(pageIndex);
	        }
	        
	        InfoContent infoContent = new InfoContent();
	        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
	        Pageable pageable = PageRequest.of(pageNo, Constants.DEFAULT_PAGESIZE, sort);
	        Page<InfoContent> page = infoContentService.findAll(pageable, infoContent);
	        
	        result.setObj(page);
	        result.setMsg("操作成功");
	        result.setFlag(true);
		return result;
		}
	
	
	@CrossOrigin(origins="*",maxAge=3600)
	@PostMapping("/productsList")
	@ResponseBody
	public JsonResult productsList(Model model, HttpServletRequest request) {
		JsonResult result=new JsonResult(false);
		 String pageIndex = WebValueUtil.getWebValue(request, "pageIndex");
		 int pageNo = 0;
	        if (StringUtils.isNotBlank(pageIndex)) {
	            pageNo = Integer.parseInt(pageIndex);
	        }
	        
	        SysProducts sysProducts = new SysProducts();
	        Sort sort = new Sort(Sort.Direction.DESC, "addTime");
	        Pageable pageable = PageRequest.of(pageNo, Constants.DEFAULT_PAGESIZE, sort);
	        Page<SysProducts> page = sysProductsService.findAll(pageable, sysProducts);
	        
	        result.setObj(page);
	        result.setMsg("操作成功");
	        result.setFlag(true);
		return result;
	}
	
	
	//查询产品详情
	@CrossOrigin(origins="*",maxAge=3600)
	@PostMapping("/toProductsOne")
	@ResponseBody
	public JsonResult toProductsOne(Model model, HttpServletRequest request) {
	
		JsonResult result=new JsonResult(false);
		 String id = WebValueUtil.getWebValue(request, "id");
		    if (StringUtils.isNotBlank(id)) {
	           
	       
	        SysProducts sysProducts = new SysProducts();
	        sysProducts=sysProductsDao.findAllById(new BigInteger(id));
//	        int num=Integer.parseInt(sysProducts.getClickMun())+1;	
	        sysProducts.setClickMun(sysProducts.getClickMun()+1);//点击量+1
	        sysProductsDao.saveAndFlush(sysProducts);
	        
	        
	     result.setMsg("操作成功");
		result.setObj(sysProducts);
		result.setFlag(true);
		return result;
		    }
		    return result;
	}
	//查询所有资讯
	@CrossOrigin(origins="*",maxAge=3600)
	@PostMapping("/toContent")
	@ResponseBody
	public JsonResult toContent(Model model, HttpServletRequest request) {
		JsonResult result=new JsonResult(false);
		 String pageIndex = WebValueUtil.getWebValue(request, "pageIndex");
	     int pageNo = 0;
	        if (StringUtils.isNotBlank(pageIndex)) {
	            pageNo = Integer.parseInt(pageIndex);
	        }
	        InfoContent infoContent = new InfoContent();
	        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
	        Pageable pageable = PageRequest.of(pageNo, Constants.DEFAULT_PAGESIZE, sort);
	        Page<InfoContent> page = infoContentService.findAll(pageable, infoContent);
	//	List<InfoContent> listInfoContent= infoContentDao.findAll();
	        Map<String,Object> obj=new HashMap<String,Object>();
	        obj.put("page", page);
	    
		result.setObj(obj);
		result.setMsg("操作成功");
		result.setFlag(true);
		return result;
		
	}
	
	@CrossOrigin(origins="*",maxAge=3600)
	@PostMapping("/getUser")
	@ResponseBody
	public JsonResult getUser(Model model, HttpServletRequest request) {
		JsonResult result=new JsonResult(false);
		 String id = WebValueUtil.getWebValue(request, "id");
//		 User user=new User();
//		 user.setId(new BigInteger(id));
		User user=userDao.findAllById(new BigInteger(id));
		 result.setObj(user);
		 result.setMsg("操作成功");
		 result.setFlag(true);
		return result;
		 
		}
	//查询资讯详情
	@CrossOrigin(origins="*",maxAge=3600)
	@PostMapping("/toContentOne")
	@ResponseBody
	public JsonResult toContentOne(Model model, HttpServletRequest request) {
		JsonResult result=new JsonResult(false);
		 String id = WebValueUtil.getWebValue(request, "id");
		 System.out.println(id);
		   if (StringUtils.isNotBlank(id)) {

		        InfoContent infoContent = new InfoContent();
		        
		        infoContent=infoContentDao.findAllById(new BigInteger(id));
		        infoContent.setClickNum(infoContent.getClickNum()+1);//点击量+1
		        infoContentDao.saveAndFlush(infoContent);
		        List<SysComment> list=sysCommentDao.findAllByContentId(infoContent);
		        
		        Map<String,Object> obj=new HashMap<String,Object>();
		       obj.put("sysCommentList", list);
		       obj.put("infOne", infoContent);
		    
			result.setObj(obj);
			result.setMsg("操作成功");
			result.setFlag(true);
			return result;
	        }else {
		return result;
		}
		}
	//发表评论
	@CrossOrigin(origins="*",maxAge=3600)
    @RequestMapping("/commentSave")
    @ResponseBody
    public JsonResult commentSave(SysComment comment,HttpServletRequest request) {
        JsonResult result = new JsonResult(false,"保存失败");
        Date date=new Date();
        comment.setCommentTime(date);
        sysCommentDao.saveAndFlush(comment);
        result.setFlag(true);
        result.setMsg("保存成功");
        return result;
    }
	
	//发现页面
	@CrossOrigin(origins="*",maxAge=3600)
    @RequestMapping("/finding")
    @ResponseBody
	public JsonResult finding(Model model, HttpServletRequest request) {
		JsonResult result=new JsonResult(false);
		 String pageIndex = WebValueUtil.getWebValue(request, "pageIndex");
	     int pageNo = 0;
	        if (StringUtils.isNotBlank(pageIndex)) {
	            pageNo = Integer.parseInt(pageIndex);
	        }
	        InfoContent infoContent = new InfoContent();
	        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
	        Pageable pageable = PageRequest.of(pageNo, Constants.DEFAULT_PAGESIZE, sort);
	        Page<InfoContent> page = infoContentService.findAll(pageable, infoContent);
	//	List<InfoContent> listInfoContent= infoContentDao.findAll();
	        Map<String,Object> obj=new HashMap<String,Object>();
	        obj.put("page", page);
	    
		result.setObj(obj);
		result.setMsg("操作成功");
		result.setFlag(true);
		return result;
		}
	//旅游页面
	@CrossOrigin(origins="*",maxAge=3600)
    @RequestMapping("/toScenic")
    @ResponseBody
	public JsonResult toScenic() {
		JsonResult result=new JsonResult(false);
		List<SysScenic> list=sysScenicDao.findAll();
		result.setObj(list);
		result.setMsg("操作成功");
		result.setFlag(true);
		return result;
	}
	
	//退出系统
	@CrossOrigin(origins="*",maxAge=3600)
    @RequestMapping("/toBack")
    @ResponseBody
	public JsonResult toBack(HttpServletRequest request,HttpServletResponse response) {
		JsonResult result=new JsonResult(false);
		HttpSession sessionOld = request.getSession(false);
		if(sessionOld != null){
			sessionOld.invalidate();
		}
		result.setMsg("清空成功");
		result.setFlag(true);
		return result;
		
	}
	//培训列表
	@CrossOrigin(origins="*",maxAge=3600)
    @RequestMapping("/toTrain")
    @ResponseBody
	public JsonResult toTrain(Model model,HttpServletRequest request) {
		JsonResult result=new JsonResult(false);
		 String pageIndex = WebValueUtil.getWebValue(request, "pageIndex");

	        //参数封装
	        int pageNo = 0;
	        if (StringUtils.isNotBlank(pageIndex)) {
	            pageNo = Integer.parseInt(pageIndex);
	        }
	        SysTraining sysTraining = new SysTraining();

	        //获取分页数据
	        Sort sort = new Sort(Sort.Direction.DESC, "addTime");
	        Pageable pageable = PageRequest.of(pageNo, Constants.DEFAULT_PAGESIZE, sort);
	        Page<SysTraining> page = sysTrainingService.findAll(pageable, sysTraining);
	    result.setObj(page);
		result.setMsg("操作成功");
		result.setFlag(true);
		return result;
		
	}
	
	//培训详情
	@CrossOrigin(origins="*",maxAge=3600)
    @RequestMapping("/toTrainOne")
    @ResponseBody
	public JsonResult toTrainOne(Model model, HttpServletRequest request) {
		JsonResult result=new JsonResult(false);
		 String id = WebValueUtil.getWebValue(request, "id");
		 if(StringUtils.isNotBlank(id)) {
			 SysTraining sysTraining=new SysTraining();
			 sysTraining=sysTrainingDao.findAllById(new BigInteger(id));
			 List<TrainComm> list=trainCommDao.findAllBySysTraining(sysTraining);
			 Map<String,Object> obj=new HashMap<>();
			 obj.put("trainComm", list);
			 obj.put("sysTraining", sysTraining);
			 result.setObj(obj);
			 result.setMsg("操作成功");
				result.setFlag(true);
				return result;
		 }else {
			 result.setMsg("请传一个id");
			 return result;
		 }

	}
	
	//发表培训评论
	@CrossOrigin(origins="*",maxAge=3600)
    @RequestMapping("/trainCommSave")
    @ResponseBody
    public JsonResult trainCommSave(TrainComm trainComm,HttpServletRequest request) {
        JsonResult result = new JsonResult(false,"保存失败");
        Date date=new Date();
        trainComm.setTrainTime(date);
        trainCommDao.saveAndFlush(trainComm);
        result.setFlag(true);
        result.setMsg("保存成功");
        return result;
    }
	
	//对培训评论的各种回复
	@CrossOrigin(origins="*",maxAge=3600)
    @RequestMapping("/toReply")
    @ResponseBody
    public JsonResult toReply(Model model, HttpServletRequest request) {
		JsonResult result=new JsonResult(false);
		 String id = WebValueUtil.getWebValue(request, "id");
		 if(StringUtils.isNotBlank(id)) {
			 TrainComm trainComm=new TrainComm();
			 trainComm.setId(new BigInteger(id));
			List<ReplyComm> list=replyCommDao.findAllByTrainComm(trainComm);
			result.setFlag(true);
			result.setMsg("操作成功");
			result.setObj(list);
		 }
		return result;
		
	}
	
	
	
	//修改个人信息接口
	@CrossOrigin(origins="*",maxAge=3600)
    @RequestMapping("/updateUser")
    @ResponseBody
	public JsonResult updateUser(User user,HttpServletRequest request) {
		JsonResult result=new JsonResult(false);
		if(user.getId()==null) {
			result.setMsg("此用户不存在");
			return result;
		}
	    if (user.getId() != null) {
           User userOld = userDao.getOne(user.getId());
            UpdateUtil.copyNonNullProperties(user, userOld);
        }
		userDao.saveAndFlush(user);
		result.setMsg("修改成功");
		result.setFlag(true);
		return result;
		
	}
	
	//预售门票列表接口
	@CrossOrigin(origins="*",maxAge=3600)
    @RequestMapping("/toPresell")
    @ResponseBody
	public JsonResult toPresell() {
		JsonResult result=new JsonResult(false);
		List<SysTicketType> list=sysTicketTypeDao.findAllByOutTicket(new BigInteger("2"));
		result.setMsg("操作成功");
		result.setObj(list);
		result.setFlag(true);
		return result;
		
	}
	//预售票详情
	@CrossOrigin(origins="*",maxAge=3600)
    @RequestMapping("/toPresellOne")
    @ResponseBody
	public JsonResult toPresellOne(Model model, HttpServletRequest request) {
		JsonResult result=new JsonResult(false);
		String id = WebValueUtil.getWebValue(request, "id");
		SysTicketType sysTicketType=new SysTicketType();
		sysTicketType=sysTicketTypeDao.findAllById(new BigInteger(id));
		result.setMsg("操作成功");
		result.setObj(sysTicketType);
		result.setFlag(true);
		return result;
		
	}
	
	//进入购票
	@CrossOrigin(origins="*",maxAge=3600)
    @RequestMapping("/toPayTicket")
    @ResponseBody
	public JsonResult toPayTicket(Model model, HttpServletRequest request) {
		JsonResult result=new JsonResult(false);
		String type = WebValueUtil.getWebValue(request, "type");
		String user = WebValueUtil.getWebValue(request, "user");
		if(StringUtils.isNotBlank(type)&&StringUtils.isNotBlank(user)) {
			User  uid=new User();
			uid.setId(new BigInteger(user));
			SysTicketType ticketType=new SysTicketType();
			ticketType.setId(new BigInteger(type));
			SysTicket ticket=new SysTicket();
			ticket.setTicketType(ticketType);
			ticket.setUserId(uid);
			ticket.setBuyTime(new Date());
			ticket.setTicketState(new BigInteger("0"));
		
		
		 String msg = RandomUtil.generateNumberString(10);//10位随机数字
	        String path =Constants.IMAGE_LOCAL_PATH+Constants.getFilePath("ticket");//存放的途径
	        File f = new File(path);
			if(!f.exists()){//生成文件夹
			    f.mkdirs(); 
			}
			String path1=path+msg+".png";//具体图片途径
	        BarcodeUtil.generateFile(msg, path1);//按照数据数生成条形码
	        ticket.setTicketNo(Constants.getFilePath("ticket")+msg+".png");
	        sysTicketDao.saveAndFlush(ticket);
	        SysTicket sysTicket=  sysTicketDao.findAllByTicketNo(Constants.getFilePath("ticket")+msg+".png");
	        result.setObj(sysTicket);
	        result.setMsg("操作成功");
	        result.setFlag(true);
	        
		}
		return result;
	}
	
	//删除订单
	@CrossOrigin(origins="*",maxAge=3600)
    @RequestMapping("/toDeleteTicket")
    @ResponseBody
	public JsonResult toDeleteTicket(Model model,HttpServletRequest request) {
		JsonResult result=new JsonResult(false);
		String id = WebValueUtil.getWebValue(request, "id");
		if(StringUtils.isNotBlank(id)) {
			if(sysTicketDao.existsById(new BigInteger(id))) {
			sysTicketDao.deleteById(new BigInteger(id));
			result.setMsg("删除成功");
			result.setFlag(true);
			}
		}
		return result;
		
	}
	
	//进入我的门票
	@CrossOrigin(origins="*",maxAge=3600)
    @RequestMapping("/toMyTicket")
    @ResponseBody
	public JsonResult toMyTicket(Model model,HttpServletRequest request) {
		JsonResult result=new JsonResult(false);
		String user = WebValueUtil.getWebValue(request, "user");
		if(StringUtils.isNotBlank(user)) {
			User uid=new User();
			uid.setId(new BigInteger(user));
			List<SysTicket> list=sysTicketDao.findAllByUserId(uid);
			result.setMsg("操作成功");
			result.setObj(list);
			result.setFlag(true);
		}
		return result;
	}
	
	//进入我的门票详情
	@CrossOrigin(origins="*",maxAge=3600)
    @RequestMapping("/toMyTicketOne")
    @ResponseBody
	public JsonResult toMyTicketOne(Model model,HttpServletRequest request) {
		JsonResult result=new JsonResult(false);
		String id = WebValueUtil.getWebValue(request, "id");
		if(StringUtils.isNotBlank(id)) {
			SysTicket ticket=sysTicketDao.findAllById(new BigInteger(id));
			result.setMsg("操作成功");
			result.setObj(ticket);
			result.setFlag(true);
		}
		return result;
	}
	
	
	//现售门票列表
	@CrossOrigin(origins="*",maxAge=3600)
    @RequestMapping("/toNowsell")
    @ResponseBody
	public JsonResult toNowsell() {
		JsonResult result=new JsonResult(false);
		List<SysTicketType> list=sysTicketTypeDao.findAllByOutTicket(new BigInteger("1"));
		result.setMsg("操作成功");
		result.setObj(list);
		result.setFlag(true);
		return result;
	}
	

	
	
	//请求天气接口并把结果返回给前端
  @CrossOrigin(origins="*",maxAge=3600)
  @RequestMapping("/toWeather")
  @ResponseBody
  public JsonResult toWeather(Model model, HttpServletRequest request) {
	  JsonResult result=new JsonResult(false);
	  String cityId = WebValueUtil.getWebValue(request, "cityId");
     // String url = "http://www.weather.com.cn/data/sk/101220101.html";
	  //String url = "http://t.weather.sojson.com/api/weather/city/101220101";
	  String url = "http://t.weather.sojson.com/api/weather/city/"+cityId;
      StringBuilder sb = new StringBuilder();
     
      try {
          URL oracle = new URL(url);
          URLConnection yc = oracle.openConnection();
          BufferedReader in = new BufferedReader(new InputStreamReader(
                  yc.getInputStream(),"utf-8"));//防止乱码
          String inputLine = null;
          while ((inputLine = in.readLine()) != null) {
              sb.append(inputLine);              
          }
          in.close();
      } catch (MalformedURLException e) {
      } catch (IOException e) {
      }
    String json=sb.toString();

    result.setMsg("接口调用完成");
    result.setObj(json);
    result.setFlag(true);
      return result;
  }
 /* @CrossOrigin(origins="*",maxAge=3600)
  @RequestMapping("userSaveImg")
  @ResponseBody
  public JsonResult userSaveImg(Model model,HttpServletRequest request) {
	  JsonResult result = new JsonResult(false,"保存失败");
	  System.out.println("进入");
	  String userImg = WebValueUtil.getWebValue(request, "userImg");
	   if(StringUtils.isBlank(userImg)) {
	    	  return result;
	      }
	  BASE64Decoder decoder = new BASE64Decoder();
	  String baseValue = userImg.replaceAll(" ", "+");
	  String[] strArr = baseValue.split("base64,");
	  String base64 = strArr[1];
	  System.out.println(base64);

	 String fileName=RandomUtil.generateLowerString(10)+".jpg";
          // Base64解码
          byte[] b;
		try {
			b = decoder.decodeBuffer(base64.replace("data:image/jpeg;base64,", ""));
			userImg = userImg.replace("base64,", "");
			//String imgFilePath = "D:\\apache-tomcate-7.0.47\\webapps\\upload\\userInfo\\"+fileName;
			String path=Constants.IMAGE_LOCAL_PATH+Constants.getFilePath("userInfoImg");
			File f = new File(path);
			if(!f.exists()){
			    f.mkdirs(); 
			}
			String localPath =path+fileName;
		     for (int i = 0; i < b.length; ++i) {
	              if (b[i] < 0) {// 调整异常数据
	                  b[i] += 256;
	                
	              }
	          }
		     OutputStream out = new FileOutputStream(localPath);
		     out.write(b);
	            out.flush();
	            out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	  result.setFlag(true);
	return result;
  }
  */
  
  @CrossOrigin(origins="*",maxAge=3600)
  @RequestMapping("userSaveInfo")
  @ResponseBody
  @SysOperateLog(operate = "保存资讯信息")
  public JsonResult userSaveInfo(InfoContent infoContent,HttpServletRequest request) {
      JsonResult result = new JsonResult(false,"保存失败");
      String userImg = WebValueUtil.getWebValue(request, "userImg");
      if(StringUtils.isBlank(userImg)) {
    	  return result;
      }
	  BASE64Decoder decoder = new BASE64Decoder();
	  String baseValue = userImg.replaceAll(" ", "+");
	 String fileName=RandomUtil.generateLowerString(10)+".jpg";//创建文件名
          // Base64解码
          byte[] b;
		try {
			b = decoder.decodeBuffer(baseValue.replace("data:image/jpeg;base64,", ""));//过滤文件头
			userImg = userImg.replace("base64,", "");//过滤不需要的字符

			String path=Constants.IMAGE_LOCAL_PATH+Constants.getFilePath("userInfoImg");//设置保存路径
			File f = new File(path);
			if(!f.exists()){
			    f.mkdirs(); 
			}
			String localPath =path+fileName;
		     for (int i = 0; i < b.length; ++i) {
	              if (b[i] < 0) {// 调整异常数据
	                  b[i] += 256;
	              }
	          }
		     OutputStream out = new FileOutputStream(localPath);//文件写入
		     out.write(b);
	            out.flush();
	            out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		infoContent.setInfoIcon( Constants.getFilePath("userInfoImg")+fileName);
		if(infoContent.getUserId()==null) {
			User user=new User();
			user.setId(new BigInteger("0"));
			infoContent.setUserId(user);
		}
		Date date=new Date();
		infoContent.setCreateTime(date);
		infoContent.setClassifyId(new BigInteger("34"));
      infoContentDao.saveAndFlush(infoContent);
      result.setFlag(true);
      result.setMsg("保存成功");
      return result;
  }
  @CrossOrigin(origins="*",maxAge=3600)
  @RequestMapping("userSaveTrain")
  @ResponseBody
  @SysOperateLog(operate = "保存培训信息")
  public JsonResult userSaveTrain(SysTraining sysTraining,@RequestParam("fileName")MultipartFile file,HttpServletRequest request,@RequestParam("file1")MultipartFile file1) {
      JsonResult result = new JsonResult(false,"保存失败");
      String trainImgOld = WebValueUtil.getWebValue(request, "trainImgOld");
     
      if(!trainImgOld.equals(sysTraining.getTrainImg())) { 
          String req= file1.getOriginalFilename();
          String imgPath = Constants.getFilePath("img")+req;
  		String localPath = Constants.IMAGE_LOCAL_PATH+Constants.getFilePath("img");
  		FileUtils.upload(file1, localPath, req);
          sysTraining.setTrainImg(imgPath);
    
     }
      if (sysTraining.getId() != null) {
      	SysTraining sysTrainingOld = sysTrainingDao.getOne(sysTraining.getId());
          UpdateUtil.copyNonNullProperties(sysTraining, sysTrainingOld);
      }
      String req= file.getOriginalFilename();
      String videoPath = Constants.getFilePath("video")+req;
		String localPath = Constants.IMAGE_LOCAL_PATH+Constants.getFilePath("video");
		
		FileUtils.upload(file, localPath, req);
		sysTraining.setTrainingVideo(videoPath);
      sysTrainingDao.save(sysTraining);
      result.setFlag(true);
      result.setMsg("保存成功");

      return result;
  }

}
